import { useState, useEffect, useCallback } from 'react';
import { Input, InputNumber, Select, Switch, Button } from 'antd';
import { useFlowStore } from '../stores/flowStore';
import { FunctionParam } from '../common/types';
import './NodeEditorModal.css';

export const NodeEditorModal = () => {
  const selectedNode = useFlowStore((state) => 
    state.nodes.find((n) => n.id === state.selectedNodeId)
  );
  const updateNodeParams = useFlowStore((state) => state.updateNodeParams);
  const setSelectedNode = useFlowStore((state) => state.setSelectedNode);
  
  const [tempParams, setTempParams] = useState<Record<string, any>>({});

  // 获取当前节点的函数定义
  const functionDef = useFlowStore((state) => 
    state.functions.find((f) => f.id === selectedNode?.functionId)
  );

  // 初始化参数
  useEffect(() => {
    if (selectedNode && functionDef) {
      const initialParams: Record<string, any> = {};
      functionDef.parameters.forEach(param => {
        initialParams[param.name] = 
          selectedNode.parameters[param.name] !== undefined
            ? selectedNode.parameters[param.name]
            : param.defaultValue;
      });
      setTempParams(initialParams);
    } else {
      setTempParams({});
    }
  }, [selectedNode, functionDef]);

  // 动态生成输入控件
  const getInputComponent = useCallback((
    param: FunctionParam,
    value: any,
    onChange: (val: any) => void
  ) => {
    const safeValue = value ?? param.defaultValue;

    switch (param.type) {
      case 'number':
        return (
          <div className="param-input-container">
            <InputNumber
              value={safeValue}
              onChange={(val) => onChange(val !== null ? val : param.defaultValue)}
              step={param.type === 'number' ? 1 : undefined}
              min={param.min}
              max={param.max}
              addonAfter={param.unit}
              style={{ width: '100%' }}
            />
          </div>
        );

      case 'boolean':
        return (
          <Switch 
            checked={!!safeValue} 
            onChange={onChange}
          />
        );

      case 'string':
        return param.options ? (
          <Select
            value={safeValue}
            onChange={onChange}
            style={{ width: '100%' }}
            options={param.options.map(opt => ({
              label: opt,
              value: opt
            }))}
          />
        ) : (
          <Input 
            value={safeValue ?? ''} 
            onChange={(e) => onChange(e.target.value)}
          />
        );

      default:
        return <Input value={String(safeValue)} disabled />;
    }
  }, []);

  // 处理参数变更
  const handleParamChange = (paramName: string, value: any) => {
    setTempParams(prev => ({
      ...prev,
      [paramName]: value
    }));
  };

  // 提交参数修改
  const handleSubmit = () => {
    if (!selectedNode || !functionDef) return;
    updateNodeParams(selectedNode.id, tempParams);
    setSelectedNode(null);
  };

  if (!selectedNode || !functionDef || Object.keys(tempParams).length === 0) {
    return null;
  }

  return (
    <div className="modal-overlay" onClick={() => setSelectedNode(null)}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h3>{functionDef.name} - 参数设置</h3>
          <Button 
            type="text" 
            icon={<span>×</span>}
            onClick={() => setSelectedNode(null)}
            className="close-btn"
          />
        </div>
        
        <div className="params-container">
          {functionDef.parameters.map((param) => (
            <div key={param.name} className="param-row">
              <div className="param-label-container">
                <label className="param-name">
                  {param.description || param.name}
                </label>
                {(param.unit || param.type) && (
                  <span className="param-meta">
                    {param.unit && <span className="param-unit">{param.unit}</span>}
                    <span className="param-type">{param.type}</span>
                  </span>
                )}
              </div>
              
              <div className="input-wrapper">
                {getInputComponent(param, tempParams[param.name], (val) => 
                  handleParamChange(param.name, val)
                )}
              </div>
            </div>
          ))}
        </div>

        <div className="modal-footer">
          <Button 
            onClick={() => setSelectedNode(null)}
            className="cancel-btn"
          >
            取消
          </Button>
          <Button 
            type="primary" 
            onClick={handleSubmit}
            className="submit-btn"
          >
            保存参数
          </Button>
        </div>
      </div>
    </div>
  );
};